package neo.core.common;
import neo.core.Constants;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;

public class CacheData extends GeneralCacheAdministrator {
	protected static final Log log = LogFactory.getLog(CacheData.class);
	private String preKey;

	public CacheData() {
		this("");
	}

	public CacheData(String preKey) {
		super(getDefaultProp());
		this.preKey = preKey;
	}

	/**
	 * 这里可添加默认参数对BaseCache进行配置
	 * @return 参数值
	 */
	public static Properties getDefaultProp() {
		Properties p = new Properties();
		/*
		//可设置初始参数
		p.setProperty("cache.event.listeners",
				"com.opensymphony.oscache.plugins.clustersupport.JavaGroupsBroadcastingListener");
		*/
		return p;
	}
	
	/*
	 * 如果使用Group，需要Override此方法
	 */
	public String[] getGroups(String myKey) {
		return null;
	}

	/**
	 * 从缓存读取值
	 * @param myKey
	 * @param refreshPeriod
	 * @return
	 */
	public Object getCacheVaule(String myKey, int refreshPeriod) {
		String cacheKey = preKey + myKey;
		Object myValue = null;
		try {
			myValue = getFromCache(cacheKey, refreshPeriod);
		} catch (NeedsRefreshException nre) {
			myValue = null;
		}
		return myValue;
	}

	/**
	 * 从缓存读取值
	 * @param myKey
	 * @return
	 */
	public Object getCacheValue(String myKey) {
		return getCacheVaule(myKey, Constants.COMMON_PERIOD);
	}

	/**
	 * 写入缓存中
	 * @param myKey
	 * @param myValue
	 */
	public void setCacheVaule(String myKey, Object myValue) {
		String cacheKey = preKey + myKey;
		putInCache(cacheKey, myValue, getGroups(myKey));
	}
	
	@Override
	public void flushEntry(String myKey) {
		super.flushEntry(preKey + myKey);
	}
}
